//
//  NewSignViewController.m
//  便签
//
//  Created by  on 2022/10/2.
//

#import "NewSignViewController.h"
#import "EditCell.h"
@interface NewSignViewController ()
@property (strong, nonatomic) IBOutlet UIView *bgView;
@property (strong, nonatomic) IBOutlet BaseTextField *input;
@property (strong, nonatomic) IBOutlet UICollectionView *collectioView;
@property (nonatomic, strong) SignModel *model;
@property (strong, nonatomic) NSMutableArray <SignModel*>*array;
@property (assign, nonatomic) NSInteger  selectNum;
@property (strong, nonatomic) NSMutableArray *imgs;
@end

@implementation NewSignViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self loadData];
}

- (void)initUI{
    self.selectNum = 10000;
    [self.collectioView registerNib:[EditCell nib] forCellWithReuseIdentifier:[EditCell ID]];
    self.bgView.bgHexColor = APP.mainColor;
}
- (void)loadData{
    NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"account"),bg_sqlValue(APP.user.account)];
    
    [SignModel bg_findAsync:nil where:where complete:^(NSArray * _Nullable array) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.array = array;
            if (self.array.count > 0) {
                self.selectNum = 0;
                self.model = self.array[0];
            }else{
                self.model.title = @"";
                self.selectNum = 10000;
                self.model.account = APP.user.account;
            }
            self.input.text = self.model.title;
            [self.collectioView reloadData];
        });
    }];;
}
-(SignModel *)model{
    if (!_model) {
        _model = [SignModel new];
    }
    return _model;
}
-(NSMutableArray *)imgs{
    if (!_imgs) {
        _imgs = [NSMutableArray array];
    }
    return _imgs;
}
- (IBAction)actionForBtn:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.model.title = self.input.text;
    if (self.model.title.length <= 0) {
        return [Toast msg:LS(@"标题不能为空")];
    }else if(self.model.cover.length <= 0){
        return [Toast msg:LS(@"请选择一个封面")];
    }
//    if (self.model.title.length > 0) {
//        NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"title"),bg_sqlValue(self.model.title)];
//        [SignModel bg_delete:nil where:where];
//    }
    WS(self)
    [self.model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself dismissViewControllerAnimated:NO completion:nil];
            if (weakself.block) {
                weakself.block(self.model);
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:notifySignUpdate object:nil];
        });
    }];
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    NSData *data = UIImageJPEGRepresentation(img, 0.5);
    [self.imgs addObject:data];
    [self.collectioView reloadData];
    NSArray *array = [[NSUserDefaults standardUserDefaults] valueForKey:localCoverKey];
    if (array == nil) {
        array = [NSArray array];
    }
    NSMutableArray *temp = [NSMutableArray arrayWithArray:array];
    [[NSUserDefaults standardUserDefaults] setValue:temp forKey:localCoverKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  self.array.count + self.imgs.count + 1;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    EditCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[EditCell ID] forIndexPath:indexPath];
    cell.btnRight.constant = 12;
    cell.btnTop.constant = 12;
    cell.btn.userInteractionEnabled = NO;
    cell.btn.selected = self.selectNum == indexPath.row;
    [cell.btn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
    [cell.btn setImage:[UIImage imageNamed:@"选中_橘色"] forState:UIControlStateSelected];
    if (indexPath.row == self.array.count + self.imgs.count) {
        cell.img.image = [UIImage imageNamed:@"add"];
    }else if (indexPath.row < self.array.count){
        cell.img.image = [UIImage imageWithData:[self.array[indexPath.row] cover]];
    }else{
        cell.img.image = [UIImage imageWithData:self.imgs[indexPath.row - self.array.count]];
    }
    cell.btn.hidden = self.array.count + self.imgs.count == indexPath.row;
    return  cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    WS(self)
    self.input.enabled = YES;
    self.input.text = @"";
    if (indexPath.row == self.array.count + self.imgs.count) {
        self.model = nil;
        SheetViewController *vc = [SheetViewController new];
        vc.withCancel = NO;
        vc.array = @[@"相机",@"从图库中选择"];
        vc.block = ^(int index, NSString * _Nonnull text) {
            [weakself ImagePicker: index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }else if (indexPath.row < self.array.count){
        self.selectNum = indexPath.row;
        self.model = self.array[indexPath.row];
        self.input.text = self.model.title;
        self.input.enabled = NO;
    }else{
        self.selectNum = indexPath.row;
        self.model = nil;
        self.model.title = @"";
        self.model.account = APP.user.account;
        self.model.ID = [NSString stringWithFormat:@"%d",(int)self.array.count];
        self.model.cover = self.imgs[indexPath.row - self.array.count];
    }
    [collectionView reloadData];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
}
#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat w = (SCREEN_WIDTH - 20 * 3) / 2;
    CGFloat h = 203 / 153.0 * w;
    return  CGSizeMake(w,h);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(20, 20, 20, 20);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}

@end
